package com.wmlive.hhvideo.heihei.websocket;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.wmlive.hhvideo.common.GlobalParams;
import com.wmlive.hhvideo.heihei.beans.splash.InitCatchData;
import com.wmlive.hhvideo.heihei.login.AccountUtil;
import com.wmlive.hhvideo.utils.HeaderUtils;
import com.wmlive.hhvideo.utils.KLog;

import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import cn.wmlive.hhvideo.rxbuslib.RxBus2;
import cn.wmlive.hhvideo.rxbuslib.RxBusSubscribe;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * 自定义websocketService
 * Created by kangzhen on 2017/7/5.
 */

public class MyWebsocketService extends Service{
    public static final String TAG = "websock_service";
    public static final String MSG = "MyWebsocketService";

    public static final String MYWEBSOCKET_CHECK_SERVER_START = "com.wmlive.hhvideo.heihei.websocket.START";
    public static final String MYWEBSOCKET_CHECK_SERVER_STOP = "com.wmlive.hhvideo.heihei.websocket.STOP";
    public static final String MYWEBSOCKET_CHECK_SERVER_RECONNECTION = "com.wmlive.hhvideo.heihei.websocket.reconnectioin";

    public static final int CODE_CLOSE = 4001;//直接关闭
    public static final int CODE_SERVER_CLOSE = 1000;//服务关闭
    public static final int CODE_TOKEN_CLOSE = 3001;//token失效

    private  int WEBSOCKET_SERVICE_STATE = STATE_IDLE;// websocket的状态
    public static final int STATE_IDLE = 0;// 闲置状态
    public static final int STATE_CONNECTING = 1;// 正在连接
    public static final int STATE_CONNECTED = 2;// 已连接上
    public static final int STATE_DISCONNECTED = 3;//断开连接(全部断开null)
    public static final int STATE_DISCONNECTED_WEBSOCKET = 33;//断开连接(websoceket 断开)
    public static final int STATE_RECONNECTION = 4;// 重新建立连接
    public static final int STATE_TOKEN_RECONNECTION = 44;// 重新建立连接
    public static final int STATE_ONMESSAGE = 6;// 消息连接

    private static int reConnectCount = 1;//websocket重连次数
    private static int reConnectTimeInterval =2000;
    private static int reConnectTimeMaxTime = 60*1000;

    //Handler
    private HandlerThread thread;
    private Looper mServiceLooper;
    private  ServiceHandler mServiceHandler;


    //myWebsocket监听
    private  MyWebsocketListener myWebsocketListener;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        //注册
        RxBus2.get().register(this);
        initMyServiceParams();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String strAction = intent.getAction();
        KLog.e(TAG,MSG+"----------onStartCommand--------"+strAction);
        if(MYWEBSOCKET_CHECK_SERVER_START.equals(strAction)){
            //开始websocket服务
            initMyServiceParams();
            //连接websocket
            mServiceHandler.sendEmptyMessageDelayed(STATE_CONNECTING,500);
        }else if(MYWEBSOCKET_CHECK_SERVER_STOP.equals(strAction)){
            //停止
            onSendClosedAllWebSocketService();
            stopSelf();
        }else if(MYWEBSOCKET_CHECK_SERVER_RECONNECTION.equals(strAction)){
            //重新连接
            onReConnectWebSocket();
        }
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus2.get().unRegister(this);
        onSendClosedAllWebSocketService();
    }

    /***
     * 停止服务
     */
    private void stopMyWebsocketServieSelf(){
        stopSelf();
    }

    /**
     * 重置MyWebsocketService参数
     */
    private void resetMyServiceParams(){
        if(myWebsocketListener!=null){
            myWebsocketListener.onClosedWebsocket();
        }
        myWebsocketListener = null;
        if(mServiceHandler!=null){
            mServiceHandler.sendEmptyMessage(STATE_DISCONNECTED_WEBSOCKET);
            mServiceHandler.removeCallbacksAndMessages(null);
            mServiceHandler = null;
        }

        try{
            if(mServiceLooper!=null){
                mServiceLooper.quit();
            }
        }catch (Exception e){

        }finally {
            mServiceLooper = null;
        }

        try {
            if (thread != null) {
                thread.quit();
            }
        }catch (Exception e){

        }finally {
            thread = null;
        }
    }
    /**
     * 初始化Services 参数信息
     */
    private void initMyServiceParams(){
        resetMyServiceParams();
        thread = new HandlerThread("WebSocket_service");
        thread.start();
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
        myWebsocketListener = null;
        myWebsocketListener = new MyWebsocketListener(mServiceHandler);
    }

    //创建websocket
    private void initMyWebSockect(){
        String strSocketServerUrl = InitCatchData.getWebsocketServerUrlOfMessage();
        if(TextUtils.isEmpty(strSocketServerUrl)){
            WEBSOCKET_SERVICE_STATE = STATE_IDLE;
            stopSelf();
            return;
        }
        WEBSOCKET_SERVICE_STATE = STATE_CONNECTING;
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10,TimeUnit.SECONDS)
                .writeTimeout(10,TimeUnit.SECONDS)
                .readTimeout(15,  TimeUnit.SECONDS)
                .pingInterval(5,TimeUnit.SECONDS)
                .build();
        String token = AccountUtil.getToken();
        Request request = null;
        Request.Builder mBuilder = null;
        String webSocketUrl = "";


        if(TextUtils.isEmpty(token)){
            webSocketUrl = strSocketServerUrl;
        }else{
            webSocketUrl = strSocketServerUrl+"?token="+token;
        }
        mBuilder = new Request.Builder().url(webSocketUrl);
        KLog.e(TAG,MSG+"--------------------url----------"+webSocketUrl);
        mBuilder
                .addHeader("app_name", HeaderUtils.getAppName())
                .addHeader("app_version", HeaderUtils.getAppVersion())
                .addHeader("os_version", HeaderUtils.getOsVersion())
                .addHeader("os_platform", HeaderUtils.getOsPlatform())
                .addHeader("device_model", HeaderUtils.getDeviceModel())
                .addHeader("device_id",HeaderUtils.getDeviceIdMsg())
                .addHeader("device_resolution", HeaderUtils.getDeviceResolution())
                .addHeader("device_ac", HeaderUtils.getDeviceAc())
                .addHeader("api_version", HeaderUtils.getApiVersion())
                .addHeader("build_number", HeaderUtils.getBuildNumber())
                .addHeader("channel", HeaderUtils.getChannel());

        request = mBuilder.build();
        client.newWebSocket(request, myWebsocketListener);

        client.dispatcher().executorService().shutdown();
    }

    /**
     * 执行websocket重新连接
     */
    private void onReConnectWebSocket(){
        WEBSOCKET_SERVICE_STATE = STATE_DISCONNECTED;
        //重新初始化websocket信息
        initMyServiceParams();
        int delayedTime = reConnectCount*reConnectTimeInterval;
        if(delayedTime>reConnectTimeMaxTime){
            delayedTime = reConnectTimeMaxTime;
        }
        ++reConnectCount;
        mServiceHandler.sendEmptyMessageDelayed(STATE_CONNECTING,delayedTime);
    }

    /**
     * token 失效的重新连接
     */
    private void onTokenReConnectWebSocket(){
        WEBSOCKET_SERVICE_STATE = STATE_DISCONNECTED;
        AccountUtil.clearAccount();
        //重新初始化websocket信息
        initMyServiceParams();
        mServiceHandler.sendEmptyMessage(STATE_CONNECTING);
    }

    /**
     * 关闭websocke
     */
    private void onClosedWebsocket(){
        if(myWebsocketListener!=null){
            myWebsocketListener.onClosedWebsocket();
        }
    }

    //===================用户主动行为=============================
    public void onSendClosedAllWebSocketService(){
        WEBSOCKET_SERVICE_STATE = STATE_DISCONNECTED;
        resetMyServiceParams();
    }




//======================处理RxBus===================
    /**
     * 处理RxBus 回调的重新信息
     */
    @RxBusSubscribe(code = STATE_RECONNECTION)
    public void onRxBusReConnection() {
        Log.e("websock_service","---------------onRxBusReConnection-----------");
       if(WEBSOCKET_SERVICE_STATE==STATE_CONNECTED){
        //已连接状态，触发重新连接
           onReConnectWebSocket();
       }
    }

    /**
     * 处理RxBus 回调的重新信息
     */
    @RxBusSubscribe(code = STATE_TOKEN_RECONNECTION)
    public void onRxBusTokenReConnection() {
        Log.e("websock_service","-------------onRxBusTokenReConnection-------------");
        if(WEBSOCKET_SERVICE_STATE==STATE_CONNECTED){
            //已连接状态，触发重新连接
            onTokenReConnectWebSocket();
        }
    }
    //================================handler===================================
    public  class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }
        @Override
        public void handleMessage(Message msg) {
            KLog.e(TAG,MSG+"----------handleMessage--------:"+msg.what);
            switch (msg.what) {
                case STATE_CONNECTING:
                    //开始连接
                    initMyWebSockect();
                    break;
                case STATE_CONNECTED:
                    //已连接成功，
                    WEBSOCKET_SERVICE_STATE = STATE_CONNECTED;
                    reConnectCount =1;
//                    sendWebsocketTestMessage();
                    break;
                case STATE_RECONNECTION:
                    //重新连接
                    onReConnectWebSocket();
                    break;
                case STATE_TOKEN_RECONNECTION:
                    //token失效重新连接
                    onTokenReConnectWebSocket();
                    break;
                case STATE_DISCONNECTED:
                    //断开连接
                    break;
                case STATE_DISCONNECTED_WEBSOCKET:
                    //关闭websocket
                    onClosedWebsocket();
                case STATE_ONMESSAGE:
                    //接受到的数据
                    try {
                        String res = (String) msg.obj;
//                        JSONObject obj = new JSONObject(res);
//                        KLog.e(TAG, MSG + "--------message-------------optInt-------:" + obj.optInt("error_code"));
//                        if(obj!=null && obj.optInt("error_code")==30001){
//                            //清除用户账号信息
//                            KLog.e(TAG, MSG + "--------message------------AccountUtil.clearAccount()--------:" + res);
//                            AccountUtil.clearAccount();
//                            RxBus2.get().send(30001, true);
//                        }else {
                            KLog.e(TAG, MSG + "--------message------:" + res);
                            MessageDistribute.getInstance().sendMessage(res);
                     //   }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
